import csv

# 检测 merged.txt 文件的编码
encoding = "utf-8"

# 读取 merged.txt 文件，构建规格到价格和链接的映射
spec_mapping = {}
try:
    with open('merged.txt', 'r', encoding=encoding) as txt_file:
        line_count = 0
        for line in txt_file:
            line_count += 1
            parts = line.strip().split('|')
            if len(parts) == 3:
                spec = parts[0]
                price = parts[1]
                link = parts[2]
                spec_mapping[spec] = (price, link)
            else:
                print(f"merged.txt 文件第 {line_count} 行格式错误: {line.strip()}")
    print(f"merged.txt 文件中有效记录数量: {len(spec_mapping)}")
except UnicodeDecodeError:
    print(f"使用 {encoding} 编码读取 merged.txt 文件时出现解码错误，请检查文件编码。")
    exit(1)

# 读取 jd.csv 文件
input_csv_file = 'jd-nike.csv'
output_csv_file = 'jd_updated.csv'
updated_rows = []

try:
    with open(input_csv_file, 'r', encoding='gbk', newline='') as csv_file:
        reader = csv.DictReader(csv_file)
        fieldnames = reader.fieldnames

        # 确保店铺价和链接列存在，如果不存在则添加
        if '店铺价' not in fieldnames:
            fieldnames.append('店铺价')
        if '链接' not in fieldnames:
            fieldnames.append('链接')

        row_count = 0
        match_count = 0
        for row in reader:
            row_count += 1
            spec = row.get('产品规格')
            found = False
            for key in spec_mapping:
                if spec in key:
                    price, link = spec_mapping[key]
                    row['店铺价'] = price
                    row['链接'] = link
                    match_count += 1
                    found = True
                    break
            if not found:
                row['店铺价'] = ''
                row['链接'] = ''
                print(f"jd.csv 文件第 {row_count} 行的产品规格 {spec} 未在 merged.txt 中找到匹配。")
            updated_rows.append(row)
        print(f"jd.csv 文件总行数: {row_count}")
        print(f"匹配到价格和链接的行数: {match_count}")
except FileNotFoundError:
    print("未找到 jd.csv 文件，请检查文件路径。")
    exit(1)
except UnicodeDecodeError:
    print("使用 gbk 编码读取 jd.csv 文件时出现解码错误，请检查文件编码。")
    exit(1)

# 将更新后的数据写入新的 CSV 文件
try:
    with open(output_csv_file, 'w', encoding='gbk', newline='') as csv_file:
        writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
        writer.writeheader()
        writer.writerows(updated_rows)
    print(f"处理完成，更新后的数据已保存到 {output_csv_file}")
except Exception as e:
    print(f"写入更新后的数据到 {output_csv_file} 时出现错误: {e}")